<template>
    <j-modal
      width="80%"
      :title="title"
      :visible.sync="editModalVisible"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      @cancel="handleCancleDbSync"
      :destroyOnClose="true"
    >
      <template slot="footer">
        <a-button @click="handleCancleDbSync">
          关闭
        </a-button>
        <a-button type="primary" :loading="syncLoading" @click="handleDbSync" >确定</a-button>
      </template>
      <div class="table-page-search-wrapper warp">
        <a-form-model layout="horizontal" labelAlign="right" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="formData" :rules="rules">
          <a-row :gutter="24">
            <a-col :xl="8" :lg="8" :md="8" :sm="24" >
              <a-form-model-item label="图表名称" prop="name">
                <a-input v-model="formData.name" placeholder="请输入图表名称"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="编码" prop="code">
                <a-input v-model="formData.code"  placeholder="请输入图表编码"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="展示模板">
                <a-select v-model="formData.displayTemplate" placeholder="请选择展示模板">
                  <a-select-option value="tab">Tab风格</a-select-option>
                  <a-select-option value="single">单排布局</a-select-option>
                  <a-select-option value="double">双排布局</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="X轴字段" prop="xaxisField">
                <a-input v-model="formData.xaxisField" placeholder="请输入X轴字段"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="分组字段" prop="groupField">
                <a-select
                  mode="tags"
                  style="width: 100%"
                  placeholder="请输入Y轴字段"
                  :open="false"
                  v-model="groupField"
                >
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24" >
              <a-form-model-item label="是否分组">
                <a-checkbox v-model="formData.isGroup" @change="isGroupChange"></a-checkbox>
              </a-form-model-item>
            </a-col>
            <a-col :xl="16" :lg="16" :md="16" :sm="24" :offset="8" v-if="!formData.isGroup">
              <a-form-model-item :label-col="{span:3}" :wrapper-col="{span:21}" label="Y轴字段" prop="yaxisField">
                <a-input v-model="formData.yaxisField" placeholder="Y轴字段"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24" >
              <a-form-model-item label="数据类型">
                <j-dict-select-tag v-model="formData.dataType" :triggerChange="true" @change="graphDataTypeChange" placeholder="请选择数据类型" dict-code="online_graph_data_type"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="16" :lg="16" :md="16" :sm="24">
              <a-form-model-item :label-col="{span:3}" :wrapper-col="{span:21}" label="图表类型" prop="graphType">
                <j-select-multiple
                  v-model="formData.graphType"
                  placeholder="请选择图表类型"
                  :options="graphTypeDictOptions"
                />
              </a-form-model-item>
            </a-col>
            <a-col :offset="8" :xl="16" :lg="16" :md="16" :sm="24" v-if="formData.graphType && formData.graphType.split(',').indexOf('treeTable')>=0">
              <a-form-model-item :label-col="{span:3}" :wrapper-col="{span:21}" label="pid" prop="pid">
                <a-input v-model="formData.pid" placeholder="请输入pid"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="是否X轴聚合">
                <a-checkbox :disabled="formData.dataType === 'sql'?false:true" v-model="formData.aggregate"></a-checkbox>
              </a-form-model-item>
            </a-col>
            <a-col :xl="16" :lg="16" :md="16" :sm="24">
              <a-form-model-item :label-col="{span:3}" :wrapper-col="{span:21}" label="数据表格描述">
                <a-input v-model="formData.annotation" placeholder="请输入描述"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item :label-col="{span:3}" :wrapper-col="{span:21}" label="描述">
                <a-input v-model="formData.content" type="textarea" placeholder="请输入描述" />
              </a-form-model-item>
            </a-col>
            <template v-if="formData.dataType === 'bean'">
              <a-col :xl="16" :lg="16" :md="16" :sm="24" >
                <a-form-model-item :label-col="{span:3}" :wrapper-col="{span:21}" label="java" prop="beanPath" >
                  <a-input v-model="formData.beanPath" type="text" placeholder="请输入java类" />
                </a-form-model-item>
              </a-col>
            </template>
          </a-row>
        </a-form-model>
        <a-form-model :rules="rules">
          <a-row :gutter="24">
            <template v-if="formData.dataType === 'sql'">
              <a-col :xl="24" :lg="24" :md="24" :sm="24" style="padding-left: 4px; padding-right: 4px;">
                <a-form-model-item label="查询SQL" style="margin-bottom: 4px;">
                  <code-mirror-lite
                    mode="sql"
                    v-model="formData.cgrSql"
                  ></code-mirror-lite>
                </a-form-model-item>
              </a-col>
              <a-col :xl="24" :lg="24" :md="24" :sm="24" style="padding-left: 12px; padding-right: 4px; text-align: right; margin-bottom: 24px;">
                <span style="float: right;overflow: hidden;">
                  <a-button  type="primary"  @click="searchSQL">SQL解析</a-button>
                </span>
              </a-col>
            </template>
            <template v-else-if="formData.dataType === 'json'">
              <a-col :xl="24" :lg="24" :md="24" :sm="24" style="padding-left: 4px; padding-right: 4px;">
                <a-form-model-item label="数据JSON" prop="cgrSql" >
                  <code-mirror-lite  v-model="formData.cgrSql"></code-mirror-lite>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :xl="24" :lg="24" :md="24" :sm="24">
              <a-form-model-item label="JS增强">
                <code-mirror-lite v-model="formData.extendJs"></code-mirror-lite>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <a-tabs defaultActiveKey="1">
          <a-tab-pane key="1" tab="列表字段">
            <config-table :extendData={diagramCode:formData.code} ref="configTable" :tableData="formData.diagramFieldConfigurationList"></config-table>
          </a-tab-pane>
        </a-tabs>
      </div>
    </j-modal>
</template>
<script>
import JSelectMultiple from '@/components/jeecg/JSelectMultiple'
import { postAction, putAction, postActionQs } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import CodeMirrorLite from '@/components/CodeMirrorLite/CodeMirrorLite'
import ConfigTable from '../components/ConfigTable'
import { CHART_LIST } from '../utils/Utils'

export default {
  name: 'OnlGraphreportHeadModal',
  components: {
    JSelectMultiple,
    CodeMirrorLite,
    ConfigTable
  },
  computed: {
    groupField: {// 分组字段双向绑定转换
      get: function() {
        return this.formData.groupField ? this.formData.groupField.split(',') : []
      },
      set: function(value) {
        this.formData.groupField = value.join(',')
      }
    }
  },
  data() {
    const isJson = function(str) {
      try {
        JSON.parse(str)
      } catch (e) {
        return false
      }
      return true
    }
    return {
      editModalVisible: false,
      title: '编辑',
      syncLoading: false,
      fullscreen: true,
      switchFullscreen: true,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      graphTypeDictOptions: CHART_LIST, // 图表类型字典
      selectedRowKeys: [],
      url: {
        list: '/online/cgform/head/list',
        edit: 'diagram/diagramConfiguration/edit',
        add: 'diagram/diagramConfiguration/add',
        parseSql: '/diagram/diagramConfiguration/parseSql'
      },
      rules: {
        name: [
          { required: true, message: '请输入图表名称', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入图表编码', trigger: 'blur' },
          { validator: (rule, value, callback) => validateDuplicateValue('cs_diagram_config', 'code', value, this.formData.id, callback) }
        ],
        xaxisField: [
          { required: true, message: '请输入X轴字段', trigger: 'change' }
        ],
        yaxisField: [
          { required: true, message: '请输入Y轴字段', trigger: 'change' }
        ],
        graphType: [
          { required: true, message: '请选择图表类型', trigger: 'change' }
        ],
        cgrSql: [
          { validator: isJson, message: 'JSON格式不正确', trigger: 'change' }
        ],
        pid: [
          { required: true, message: '请输入pid', trigger: 'change' }
        ],
        groupField: [
          { required: true, message: '请输入分组字段', trigger: 'change' }
        ],
        beanPath: [
          { required: true, message: '请输入Java', trigger: 'change' }
        ]
      },
      formData: {
        'isCombination': '',
        'displayTemplate': '',
        'code': '',
        'graphType': '',
        'dataType': 'sql',
        'yaxisField': '',
        'updateTime': '',
        'content': null,
        'cgrSql': '',
        'createBy': '',
        'extendJs': null,
        'createTime': '',
        'updateBy': '',
        'name': '',
        'yaxisText': '',
        'id': null,
        'pid': null,
        'xaxisField': '',
        'aggregate': false,
        'annotation': '',
        'groupField': '',
        'isGroup': true,
        'beanPath': '',
        'diagramFieldConfigurationList': []
      },
      newFormData: {// 新增用数据
        'isCombination': '',
        'displayTemplate': 'tab',
        'code': '',
        'graphType': '',
        'dataType': 'json',
        'yaxisField': '',
        'updateTime': '',
        'content': null,
        'cgrSql': '',
        'createBy': '',
        'extendJs': '',
        'createTime': '',
        'updateBy': '',
        'name': '',
        'yaxisText': '',
        'id': null,
        'pid': null,
        'xaxisField': '',
        'aggregate': false,
        'annotation': '',
        'isGroup': true,
        'diagramFieldConfigurationList': []
      },
      disableSubmit: false
    }
  },
  methods: {
    handleCancleDbSync() { // 关闭
      this.editModalVisible = false
    },
    edit(record) {
      var that = this
      const record_ = JSON.parse(JSON.stringify(record))
      Object.keys(that.formData).forEach(function(key) {
        that.formData[key] = record_[key]
      })
      this.editModalVisible = true
    },
    add() {
      var that = this
      const record_ = JSON.parse(JSON.stringify(that.newFormData))
      Object.keys(that.formData).forEach(function(key) {
        that.formData[key] = record_[key]
      })
      this.editModalVisible = true
    },
    handleDbSync() { // 弹窗点击确定
      const configTable = this.$refs.configTable.getTableData()
      this.formData.diagramFieldConfigurationList = configTable
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.updateData()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    updateData(params) { // 保存提交数据
      this.syncLoading = true
      if (this.formData.id) {
        putAction(this.url.edit, this.formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('modalFormOk')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.syncLoading = false
        })
      } else {
        postAction(this.url.add, this.formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('modalFormOk')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.syncLoading = false
        })
      }
    },
    searchSQL() { // SQL解析
      postActionQs(this.url.parseSql, { sql: this.formData.cgrSql }).then((res) => {
        if (res.code === 200) {
          this.$message.info(res.message)
          var that = this
          this.$refs.configTable.clearTableData()
          res.result.forEach(function(item, i) {
            that.$refs.configTable.handleAddGraphRepoart({
              fieldName: item,
              orderNum: i
            })
          })
        } else {
          this.$message.error(res.message)
        }
      })
    },
    graphDataTypeChange(val) {
      this.formData.dataType = val
      if (val === 'json') {
        this.formData.aggregate = false
      }
    },
    isGroupChange(event) { // 是否分组切换
      const graphType = []
      if (!event.target.checked) {
        var list = this.formData.graphType.split(',')
        list.forEach((item, i) => {
          if (['bar', 'line', 'barStack', 'transverseBarMuiltid'].indexOf(item) >= 0) {
            graphType.push(item)
          }
        })
        this.formData.graphType = graphType.join(',')
      }
      this.graphTypeDictOptions.forEach((item, i) => {
        item.disabled = ['bar', 'line', 'barStack', 'transverseBarMuiltid'].indexOf(item.value) < 0 && !event.target.checked
      })
    }
  }
}
</script>
<style lang="less">
.warp .ant-select{
  width: 100%;
}
.warp .table-operator{
  margin-bottom: 10px;
}
.ant-card-body .warp {
  padding: 10px;
}
.warp .table-operator .ant-btn{
  margin: 0px 8px 0 0 !important;
}
.ant-card-body .warp  .table-operator{
  margin-bottom:10px !important;
}
</style>
